// eslint-disable-next-line no-undef
const fs = require('fs')
// eslint-disable-next-line no-undef
const path = require('path')
// eslint-disable-next-line no-undef
const Jimp = require('jimp')

window.service = {
  getPath: () => {
    return path
  },
  readDirectory: (directory, callback) => {
    // 读取文件目录（异步）
    fs.readdir(directory, (error, files) => {
      if (error) {
        callback(error, null)
      } else {
        callback(null, files)
      }
    })
  },
  readDirectorySync: (directory) => {
    // 读取文件目录（同步）
    try {
      return fs.readdirSync(directory)
    } catch (error) {
      console.error(error)
    }
    return null
  },
  createDirectory: (directory, callback) => {
    //创建文件夹
    if (!fs.existsSync(directory)) {
      fs.mkdir(directory, (error) => {
        if (error) {
          callback(error)
        } else {
          callback(null)
        }
      })
    } else {
      callback(null)
    }
  },
  resizeExtension: (inputPath, outputPath, extension) => {
    // 修改图片后缀
    const outputFilePath = extension ? outputPath.replace(/\.[^.]+$/, `.${extension}`) : outputPath
    Jimp.read(inputPath, (err, image) => {
      if (err) throw err
      image.write(outputFilePath)
    })
  },
  resizeImage: (inputPath, outputPath, size, extension) => {
    //修改图片尺寸
    const outputFilePath = extension ? outputPath.replace(/\.[^.]+$/, `.${extension}`) : outputPath
    Jimp.read(inputPath, (err, image) => {
      if (err) throw err
      let _width = size.width ? size.width : Jimp.AUTO
      let _height = size.height ? size.height : Jimp.AUTO
      if (size.quality && size.quality > 0 && size.quality <= 100) {
        image.resize(_width, _height).quality(size.quality).write(outputFilePath)
      } else {
        image.resize(_width, _height).write(outputFilePath)
      }
    })
  }
}
